<template>


    <el-card v-loading="loading">
        <template #header>
            <div class="card-header">
                <div class="buttons">
                    <div class="mb-4">
                        <el-button type="primary" round @click="addNew">新增</el-button>
                        <el-button type="success" round @click="update">修改</el-button>
                        <el-button type="danger" round @click="handeleDelete">删除</el-button>
                        <el-button type="warning" round @click="toggleSelection()">清空选择</el-button>
                    </div>
                </div>
            </div>
        </template>
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%; height: 800px;"
            @selection-change="handleSelectionChange" @row-click="handleRowChick" row-key="id">
            <el-table-column type="selection" width="55" />
            <el-table-column property="username" label="用户名" width="120" />
            <el-table-column property="nickName" label="昵称" width="120" />
            <el-table-column property="gender" label="性别" width="120" />
            <el-table-column property="phone" label="电话" width="120" />
            <el-table-column property="email" label="邮箱" width="240" />
            <el-table-column property="dept.name" label="部门" width="120" />
            <el-table-column label="角色" width="120">
                <template #default="scope">
                    <p v-for="item in tableData[scope.$index].roles">{{ item.name }}</p>
                </template>

            </el-table-column>
            <el-table-column label="岗位" width="120">
                <template #default="scope">
                    <p v-for="item in tableData[scope.$index].jobs">{{ item.name }}</p>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="120">
                <template #default="scope">
                    <el-switch v-model="scope.row.enabled" class="ml-2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        @change="changeEnable(scope.row)" />
                </template>

            </el-table-column>
            <el-table-column property="createTime" label="创建时间" width="240" />
        </el-table>
        <template #footer>
            <div class="example-pagination-block">
                <el-pagination layout="prev, pager, next" :default-page-size="pageSize"
                    v-model:current-page="currentPage" :total="totalSize" @current-change="getUserByPage" />
            </div>
        </template>
    </el-card>



    <!-- 更新员工表单 -->
    <el-drawer v-model="drawer_update" title="修改员工">
        <el-form ref="updateFormRef" style="max-width: 600px" :model="updateForm" :rules="updaterules"
            label-width="auto" class="demo-ruleForm" status-icon>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="updateForm.username" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
                <el-input v-model="updateForm.nickName" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-input v-model="updateForm.gender" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="updateForm.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="updateForm.email" />
            </el-form-item>
            <el-form-item label="角色" prop="roles">
                <el-select v-model="updateForm.roles" multiple @visible-change="getRoleOptions" :loading="loadingRoles"
                    placeholder="请选择角色" style="width: 240px">
                    <el-option v-for="item in optionsRoles" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="岗位" prop="jobs">
                <el-select v-model="updateForm.jobs" multiple @visible-change="getJobOptions" :loading="loadingJobs"
                    placeholder="请选择岗位" style="width: 240px">
                    <el-option v-for="item in optionsJobs" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="dept">
                <el-tree-select v-model="updateForm.dept" :data="optionsDept" check-strictly
                    @visible-change="getDeptOptions" :loading="loadingDept" :props="defaultProps" placeholder="请选择部门"
                    style="width: 240px" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="updateForm.password" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitUpdateForm(updateFormRef)">
                    提交
                </el-button>
                <el-button @click="resetUpdateForm(updateFormRef)">重置表单</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

    <!-- 新建员工 -->
    <el-drawer v-model="drawer_new" title="新建员工">
        <el-form ref="newFormRef" style="max-width: 600px" :model="newForm" :rules="newrules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="newForm.username" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
                <el-input v-model="newForm.nickName" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-input v-model="newForm.gender" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="newForm.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="newForm.email" />
            </el-form-item>
            <el-form-item label="角色" prop="roles">
                <el-select v-model="newForm.roles" multiple @visible-change="getRoleOptions" :loading="loadingRoles"
                    placeholder="请选择角色" style="width: 240px">
                    <el-option v-for="item in optionsRoles" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="岗位" prop="jobs">
                <el-select v-model="newForm.jobs" multiple @visible-change="getJobOptions" :loading="loadingJobs"
                    placeholder="请选择岗位" style="width: 240px">
                    <el-option v-for="item in optionsJobs" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="dept">
                <el-tree-select v-model="newForm.dept" :data="optionsDept" check-strictly
                    @visible-change="getDeptOptions" :loading="loadingDept" :props="defaultProps" placeholder="请选择部门"
                    style="width: 240px" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="newForm.password" placeholder="若不填写则默认为123456" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitNewForm(newFormRef)">
                    提交
                </el-button>
                <el-button @click="resetNewForm(newFormRef)">重置表单</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>


</template>

<script lang="ts" setup>
import { nextTick, onBeforeMount, reactive, ref } from 'vue'
import { ElTable, ElNotification } from 'element-plus'
import { createEmployee, updateEmployee, deleteEmployee, getEmployeeByPage } from '@/api/employee';
import { getJobByPage } from '@/api/job';
import { getDept } from '@/api/dept';
import { getRoleByPage } from '@/api/role';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'


const getRow = (data) => {
    console.log(data)
}

interface User {
    username: string
    nickName: string
    gender: string
    phone: string
    email: string
    enabled: boolean
    createTime: string
    id: string
    password: string
    roles: Array<object>
    dept: object
    jobs: Array<object>
}

const jobsProps = {
    label: 'name',
    value: 'id'
}

const defaultProps = {
    children: 'children',
    label: 'name',
    value: 'id'
}

const drawer_new = ref(false)
const drawer_update = ref(false)
const optionsDept = ref([])
const optionsJobs = ref([])
const optionsRoles = ref([])

const loadingJobs = ref(false)
const loadingDept = ref(false)
const loadingRoles = ref(false)


const getJobOptions = async () => {
    loadingJobs.value = true
    optionsJobs.value.length = 0
    const res = await getJobByPage({
        page: 0,
        size: 100
    })
    if (res.status == '200') {
        for (let i of res.data.content) {
            optionsJobs.value.push(i)
        }
    }
    console.log(optionsJobs)
    loadingJobs.value = false
}

const getDeptOptions = async () => {
    optionsDept.value.length = 0
    loadingDept.value = true
    const res = await getDept()
    if (res.status == '200') {
        treeHandler(res.data)
    }
    loadingDept.value = false
}

const getRoleOptions = async () => {
    loadingRoles.value = true
    optionsRoles.value.length = 0
    const res = await getRoleByPage({
        page: 0,
        size: 100
    })
    if (res.status == '200') {
        for (let i of res.data.content) {
            optionsRoles.value.push(i)
        }
    }
    loadingRoles.value = false
}

const treeHandler = (datas) => {
    optionsDept.value.length = 0
    optionsDept.value.push({
        name: "顶级部门(无上级部门)",
        createTime: "",
        enabled: true,
        id: "-1",
        pid: '-1',
        leaf: true
    })
    for (let i = 0; i < datas.length; i++) {
        if (datas[i].pid == null) {
            optionsDept.value.push({
                name: datas[i].name,
                createTime: datas[i].createTime,
                enabled: datas[i].enabled,
                id: datas[i].id,
                pid: '-1',
                leaf: datas[i].leaf
            })
            datas.splice(i, 1)
            i--
        }

    }
    optionsDept.value.forEach(x => treeBuilder(x, datas))

}

const treeBuilder = (target, datas) => {
    if (!target.leaf) {
        for (let i = 0; i < datas.length; i++) {
            if (datas[i].pid == target.id) {
                if (target.children != null) {
                    target.children.push(datas[i])
                } else {
                    target.children = [datas[i]]
                }
                const temp = datas[i]
                datas.splice(i, 1)
                i--
                if (!temp.leaf) {
                    treeBuilder(temp, datas)
                }
            }
        }
    }
}

function addNew() {
    drawer_new.value = true;
}

function update() {
    if (multipleSelection.value.length != 1) {
        ElNotification({
            title: "Warning",
            message: "请选择单个用户",
            type: "warning"
        })
    } else {
        drawer_update.value = true;
    }

}

const newFormRef = ref<FormInstance>()
const newForm = reactive<User>({
    username: '',
    nickName: '',
    gender: '',
    phone: '',
    email: '',
    enabled: true,
    createTime: '',
    id: '',
    password: '',
    roles: [],
    dept: {},
    jobs: []
})

const updateFormRef = ref<FormInstance>()
const updateForm = reactive<User>({
    username: '',
    nickName: '',
    gender: '',
    phone: '',
    email: '',
    enabled: true,
    createTime: '',
    id: '',
    password: '',
    roles: [],
    dept: {},
    jobs: []
})

const newrules = reactive<FormRules<User>>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ],
    nickName: [
        {
            required: true,
            message: '请输入昵称',
            trigger: 'blur',
        },
    ],
    gender: [
        {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
        },
    ],
    phone: [
        {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur',
        },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }

    ],
    email: [
        {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
        },
        { pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/, message: '邮箱格式不正确', trigger: 'blur' }

    ],
    password: [
        { min: 6, max: 20, message: '长度应在3到20个字符之间', trigger: 'change' },
    ]
})

const updaterules = reactive<FormRules<User>>({
    username: [
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ],
    phone: [
        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }

    ],
    email: [
        { pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/, message: '邮箱格式不正确', trigger: 'blur' }

    ],
    password: [
        { min: 6, max: 20, message: '长度应在3到20个字符之间', trigger: 'change' },
    ]
})


const submitUpdateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true
            let temp: User = {
                id: multipleSelection.value[0].id,
                username: updateForm.username || multipleSelection.value[0].username,
                nickName: updateForm.nickName || multipleSelection.value[0].nickName,
                gender: updateForm.gender || multipleSelection.value[0].gender,
                phone: updateForm.phone || multipleSelection.value[0].phone,
                email: updateForm.email || multipleSelection.value[0].email,
                createTime: multipleSelection.value[0].createTime,
                enabled: multipleSelection.value[0].enabled,
                password: updateForm.password || multipleSelection.value[0].password,
                jobs: [],
                dept: {},
                roles: []
            }
            if (updateForm.jobs.length != 0) {
                for (let i of updateForm.jobs) {
                    temp.jobs.push({ id: i })
                }
            } else {
                for (let i of multipleSelection.value[0].jobs) {
                    temp.jobs.push({ id: i.id })
                }
            }
            if (updateForm.roles.length != 0) {
                for (let i of updateForm.roles) {
                    temp.roles.push({ id: i })
                }
            } else {
                for (let i of multipleSelection.value[0].roles) {
                    temp.roles.push({ id: i.id })
                }
            }

            if (updateForm.dept.id != null) {
                temp.dept = { id: updateForm.dept.id }
            } else {
                temp.dept = { id: multipleSelection.value[0].dept.id }
            }
            const res = await updateEmployee(temp);
            if (res.status == '204') {
                ElNotification({
                    title: 'Success',
                    message: "修改成功",
                    type: 'success'
                })
                getUserByPage()
                drawer_update.value = false
            }
        } else {
            console.log('error submit!', fields)
        }
        loading.value = false
    })
}

const resetUpdateForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const submitNewForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let temp: User = {
                id: "",
                username: newForm.username,
                nickName: newForm.nickName,
                gender: newForm.gender,
                phone: newForm.phone,
                email: newForm.email,
                createTime: "",
                enabled: true,
                jobs: [],
                dept: {},
                roles: [],
                password: ''
            }
            for (let i of newForm.jobs) {
                temp.jobs.push({ id: i })
            }
            for (let i of newForm.roles) {
                temp.roles.push({ id: i })
            }
            if (newForm.dept != null) {
                temp.dept = { id: newForm.dept }
            }
            temp.password = newForm.password || '123456';
            const res = await createEmployee(temp);
            if (res.status == '201') {
                ElNotification({
                    title: "Success",
                    type: "success",
                    message: "添加成功"
                })
                drawer_new.value = false
                getUserByPage()
            } else {
                ElNotification({
                    type: "error",
                    title: "Error",
                    message: '添加失败' + res.data.message
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetNewForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}


// 列表管理Starte
const pageSize = 7;
const totalSize = ref(1);
const currentPage = ref(1);
const loading = ref(false)
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const toggleSelection = (rows?: User[]) => {
    if (rows) {
        rows.forEach((row) => {
            multipleTableRef.value!.toggleRowSelection(row, undefined)
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }
}

const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}
const handleRowChick = (row) => {
    const selected = multipleSelection.value.some((item) => item.id === row.id)
    if (!selected) {
        multipleSelection.value.push(row)
        multipleTableRef.value.toggleRowSelection(row, true)
    } else {
        const finArr = multipleSelection.value.filter((item) => {
            return item.id !== row.id
        })
        multipleSelection.value = finArr
        multipleTableRef.value.toggleRowSelection(row, false)
    }
}

const tableData: User[] = reactive([

])


const getUserByPage = async () => {
    let params = {
        page: currentPage.value - 1,
        size: pageSize
    }
    loading.value = true
    tableData.length = 0
    const res = await getEmployeeByPage(params)
    if (res != null) {
        if (res.status == '200') {
            console.log("获取成功，当前页码：", currentPage.value, "当前页面大小：", pageSize)
            const data = res.data
            totalSize.value = data.totalElements
            for (let i of data.content) {
                tableData.push(i)
            }

        } else {
            console.log("获取失败，当前页码：", currentPage.value, "当前页面大小：", pageSize)
        }
    } else {
        console.log("请求失败")
    }
    nextTick(() => {
        loading.value = false
    })
    console.log(tableData)
}
//列表管理end

const changeEnable = async (target) => {
    let temp: User = {
        username: target.username,
        nickName: target.nickName,
        gender: target.gender,
        phone: target.phone,
        email: target.email,
        enabled: target.enabled,
        createTime: target.createTime,
        id: target.id,
        password: target.password,
        roles: [{ id: "1" }],
        dept: { id: "2" },
        jobs: [{ id: "11" }]
    }
    const res = await updateEmployee(temp);
    if (res.status == '204') {
        ElNotification({
            title: "Success",
            type: "success",
            message: "用户状态更改成功"
        })
    } else {
        ElNotification({
            title: "Error",
            type: "error",
            message: "用户状态更改失败"
        })
        temp = tableData.find(x => x.id == temp.id)
        temp.enabled = !temp.enabled
    }
}

const handeleDelete = async () => {
    if (multipleSelection.value.length <= 0) {
        ElNotification({
            title: "Warning",
            type: "warning",
            message: "请选择删除对象"
        })
        return
    }
    let deleteArray = []
    for (let i of multipleSelection.value) {
        if (i.id == '1') {
            ElNotification({
                title: "Warning",
                type: "warning",
                message: "不能删除超级管理员"
            })
            return
        }
        deleteArray.push(i.id)
    }
    loading.value = true;
    const res = await deleteEmployee(deleteArray);
    if (res.status == "200") {
        getUserByPage();
        ElNotification({
            title: "Success",
            type: "success",
            message: "删除成功"
        })
    } else {
        ElNotification({
            title: "Error",
            type: "error",
            message: "删除失败"
        })
    }
}

onBeforeMount(() => {
    getUserByPage()
})
</script>

<style scoped>
.example-pagination-block+.example-pagination-block {
    margin-top: 10px;
}

.example-pagination-block .example-demonstration {
    margin-bottom: 16px;
}
</style>